/**
 * @CSVConfig.as
 *
 * @author sodaChen mail:sujun10#21cn.com
 * @version 1.0
 * <br>Copyright (C), 2014 FeiYin.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:Lion3D
 * <br>Date:2014-3-5
 */
package com.asframe.conf
{
	import com.asframe.pattern.Singleton;
	import com.asframe.ref.Type;
	import com.asframe.utils.ClassUtils;
	import com.asframe.utils.RefUtils;
	import com.asframe.utils.StringUtils;

	import flash.system.ApplicationDomain;

	/**
	 * CSV配置文件的解析和自动填充对象
	 * @author sodaChen
	 * Date:2014-3-5
	 */
	public class CSVConfig extends Singleton
	{

		private static var instance:CSVConfig;
		/**
		 * 获取实例的静态方法实例
		 * @return
		 *
		 */
		public static function getInstance():CSVConfig
		{
			if(instance == null)
			{
				instance = new CSVConfig();
			}
			return instance;
		}

		public function csvToObject( config:String,
									 resultClass:Class = null,
									 containerClass:* = null,
									 applicationDomain:ApplicationDomain = null):*
		{
			if(containerClass == null)
				containerClass = Array;
			//先进行切割
			var contentArray:Array = config.split("\r\n");
			var start:int = 2;
			if(resultClass == null)
			{
				// 第一次行
				var classPath:String = contentArray[0];
				//如果有",",表示是实际的数据
				if(classPath != null && classPath != "" && classPath.indexOf(",") == -1)
				{
//					if(classPath.indexOf("type:") != -1)
//						var temps:Array = classPath.split(":");
					resultClass = ClassUtils.forName(classPath,applicationDomain);
					start = 3;
				}
			}
			var type:Type = null;
			var isAry:Boolean = false;
			if(resultClass != Object)
			{
				if(!(resultClass is Array))
					type = Type.forClass(resultClass);
			}
			//名称的行数
			var keys:Array = contentArray[start - 2].split(",");
			var keyLen:int = keys.length;
			//做一下规则检测
			var len:int = contentArray.length;
			var resultAry:* = null;
			if(containerClass is Class)
				resultAry = new containerClass();
			else
				resultAry = containerClass;
			var values:Array = null;
			var result:* = null;
			for (var i:int = start; i < len; i++)
			{
				if(contentArray[i] == "")
				{
					continue;
				}
				values = contentArray[i].split(",");
				if(values.length < 0)
				{
					continue;
				}
				result = new resultClass();
				resultAry.push(result);
				for (var j:int = 0; j < keyLen; j++)
				{
					var name:String = StringUtils.trim(keys[j]);
					if(name == "")
						throw new Error("解析CSV出现错误，" + j + "纵列没有对应的key值");
					var value:String = StringUtils.trim(values[j]);
					var typeValue:String = null;
					if(result is Array)
						result.push(value);
					else
						result[name] = RefUtils.valueByType(name,value,type);
				}
			}
			return resultAry;
		}
	}
}